package com.badibadi.mytools;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ViewHolder {
	final View mRoot;
	// 缓存item中各个view , 省去下次findviewbyid
	final SparseArray<View> mViews = new SparseArray<View>();

	public ViewHolder(View root) {
		this.mRoot = root;
	}

	@SuppressWarnings("unchecked")
	public <T extends View> T getViewById(int id) {
		T view = (T) mViews.get(id);
		if (view == null) {
			mViews.put(id, (view = (T) mRoot.findViewById(id)));
			if (view == null)
				throw new NullPointerException("Cannot find requested view id "
						+ String.valueOf(id));
		}
		return view;
	}

	public boolean hasView(int id) {
		if (mViews.get(id) != null)
			return true;
		else {
			View view = this.mRoot.findViewById(id);
			if (view == null)
				return false;
			else {
				mViews.put(id, view);
				return true;
			}
		}
	}

	// 把组装xml view的 函数抽取出来
	public static View buildView(Context context, int redId, ViewGroup parent) {
		View view = LayoutInflater.from(context).inflate(redId, parent, false);
		view.setTag(new ViewHolder(view));
		return view;
	}

}